package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MemberDao;
import com.itheima.pojo.Member;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    MemberDao memberDao;

    /**
     * 移动端登录
     */
    @Override
    public void msmLogin(String telephone) {
        Member member = memberDao.findByTelephone(telephone);

        //如果没有会员，自动注册会员
        if (member == null) {
            member = new Member();
            member.setRegTime(new Date());
            member.setPhoneNumber(telephone);
            memberDao.add(member);
        }

    }

    /**
     * 获取会员统计数据
     * map
     *      months:['2019-12','2020-03']
     *      memberCount:[10,20,30,40]
     */
    @Override
    public Map<String, Object> getMemberReport() throws Exception {

        List<String> months = new ArrayList<>();

        //创建日历
        Calendar calendar = Calendar.getInstance();


        //返回12个月以前
        calendar.add(Calendar.MONTH,-12);

        for (int i = 0; i < 12; i++) {
            //把Date类型转换成字符串类型  2018-12  2019-01 2019-02
            String str = DateUtils.parseDate2String(calendar.getTime(),"yyyy-MM");
            //前移一个月
            calendar.add(Calendar.MONTH,1);
            months.add(str);
        }

        //统计每个月月底的会员数量
        List<Long> memberCount = new ArrayList<>();

        for (String month : months) {
            month += "-31";
            Long count = memberDao.findCountByMonth(month);
            memberCount.add(count);
        }

        Map<String,Object> map = new HashMap<>();
        map.put("months",months);
        map.put("memberCount",memberCount);

        return map;
    }

    /**
     * 获取会员统计数据--根据时间段范围--折线图
     * map
     *    months:['2019-12','2020-01','2020-02','2020-03']
     *    memberCount:[10,20,30,40]
     */
    @Override
    public Map<String, Object> getMemberReportByDate(List<Date> date) throws Exception {
        //获取前端传递过来的日期
        String startDate = DateUtils.parseDate2String(date.get(0), "yyyy-MM");
        String endDate = DateUtils.parseDate2String(date.get(1), "yyyy-MM");

        List<String> months = getMonthByDate(startDate, endDate);

        //统计每个月月底的会员数量
        List<Long> memberCount = new ArrayList<>();

        for (String month : months) {
            month += "-31";
            Long count = memberDao.findCountByMonth(month);
            memberCount.add(count);
        }

        //封装返回结果
        Map<String, Object> map = new HashMap<>();
        map.put("months", months);
        map.put("memberCount", memberCount);

        return map;
    }

    /**
     * 根据会员性别展示--饼状图
     *
     * memberSex:['男','女']
     * memberCount:[
     *             {value:335, name:'男'},
     *             {value:310, name:'女'},
     *             ]
     */
    @Override
    public Map<String, Object> getMemberSex() {
        List<String> memberSex = new ArrayList<>();
        memberSex.add("男");
        memberSex.add("女");

        Long countMan = memberDao.findBySex("1");
        Long countWoMan = memberDao.findBySex("2");

        Map<String,Object> mapMan = new HashMap<>();
        mapMan.put("name","男");
        mapMan.put("value",countMan);
        Map<String,Object> mapWoMan = new HashMap<>();
        mapWoMan.put("name","女");
        mapWoMan.put("value",countWoMan);

        List<Map<String,Object>> memberCount = new ArrayList<>();
        memberCount.add(mapMan);
        memberCount.add(mapWoMan);

        //封装返回数据
        Map<String,Object> map = new HashMap<>();
        map.put("memberSex",memberSex);
        map.put("memberCount",memberCount);

        return map;
    }

    //会员各个年龄段的占比
    @Override
    public List<Map<String, Object>> getAgeReport() throws Exception {

        List<String> idCards = memberDao.findAllIdCard();

        List<Map<String, Object>> mapList = new ArrayList<>();

        Map<String, Object> map1 = new HashMap<>();
        Map<String, Object> map2 = new HashMap<>();
        Map<String, Object> map3 = new HashMap<>();
        Map<String, Object> map4 = new HashMap<>();

        for (String idCard : idCards) {

            //从数据库中获取年份
            Integer dateDB = Integer.valueOf(idCard.substring(6,10));

            //获取当前年份
            Date today = DateUtils.getToday();
            Integer dateNew = Integer.valueOf(DateUtils.parseDate2String(today, "yyyy"));

            int age = dateNew - dateDB;

            if (age >= 0 && age <= 18){
                map1.put("name","0-18岁");

                putValue(map1);
            }else if (age >= 18 && age <= 30){
                map2.put("name","18-30岁");

                putValue(map2);
            }else if (age >= 30 && age <= 45){
                map3.put("name","30-45岁");

                putValue(map3);
            }else {
                map4.put("name","45岁以上");

                putValue(map4);
            }


        }

        mapList.add(map1);
        mapList.add(map2);
        mapList.add(map3);
        mapList.add(map4);

        return mapList;
    }


    /**
     * 传递时间范围，返回范围内的每个月份
     * @param startDate "2019-01"
     * @param endDate  "2019-12"
     * @return
     * @throws ParseException
     */
    public List<String> getMonthByDate(String startDate, String endDate) throws ParseException {
        List<String> list = new ArrayList<>();

        Date d1 = new SimpleDateFormat("yyyy-MM").parse(startDate);//定义起始日期

        Date d2 = new SimpleDateFormat("yyyy-MM").parse(endDate);//定义结束日期

        Calendar dd = Calendar.getInstance();//定义日期实例

        dd.setTime(d1);//设置日期起始时间
        while (dd.getTime().before(d2) || dd.getTime().equals(d2)) {//判断是否到结束日期

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

            String str = sdf.format(dd.getTime());

            //System.out.println(str);//输出日期结果

            dd.add(Calendar.MONTH, 1);//进行当前日期月份加1
            list.add(str);
        }
        return list;

    }

    /**
     * 在map中存入value
     *   如果在这个年龄段，记录+1
     * @param map
     */
    public void putValue(Map<String, Object> map){

        Integer value = (Integer) map.get("value");

        if(value == null ){

            value = 0;
        }

        map.put("value",value + 1);
    }
}
